package com.zpl.common.support.invoke.impl;

import com.zpl.common.rpc.RpcMessageDto;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/9/8 12:44
 */
public class TimeoutCheckThread implements Runnable{

    /**
     * 请求信息
     */
    private final ConcurrentHashMap<String, Long> requestMap;

    /**
     * 响应信息
     */
    private final ConcurrentHashMap<String, RpcMessageDto> responseMap;

    /**
     * 新建
     * @param requestMap 请求 map
     * @param responseMap 响应 map
     */
    public TimeoutCheckThread(ConcurrentHashMap<String, Long> requestMap,
                              ConcurrentHashMap<String, RpcMessageDto> responseMap) {
        if (responseMap == null) {
            throw new IllegalArgumentException("requestMap" + " can not be null!");

        }
        this.requestMap = requestMap;
        this.responseMap = responseMap;
    }
    
    @Override
    public void run() {
        for (Map.Entry<String, Long> entry : requestMap.entrySet()) {
            Long expireTime = entry.getValue();
            long currentTime = System.currentTimeMillis();
            
            if (currentTime > expireTime) {
                final String key = entry.getKey();
                // 结果设置为超时，从请求 map 中移除
                responseMap.putIfAbsent(key, RpcMessageDto.timeout());
                requestMap.remove(key);
            }
        }
    }
}
